{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3770b955",
   "metadata": {},
   "source": [
    "# 张量\n",
    "\n",
    "参考：[ndarray](https://zh.d2l.ai/chapter_preliminaries/ndarray.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11dcfa46",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "from tvm.relax.frontend.nn import Tensor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5b69fad8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tensor([1, 10], \"float32\")"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 生成1x10的随机矩阵，数值范围[0,1)，默认dtype为float64\n",
    "x = np.random.rand(1, 10)\n",
    "assert x.dtype == np.float64  # 确保数据类型为float64\n",
    "# 从numpy常量创建Tensor对象（预期自动转换为float32）\n",
    "tensor_x = Tensor.from_const(x)\n",
    "\n",
    "# 验证Tensor元数据（基于from_const的实现逻辑）\n",
    "assert tensor_x.shape == [1, 10]  # 保持原始维度\n",
    "assert tensor_x.ndim == 2         # 二维张量\n",
    "assert tensor_x.dtype == \"float32\" # 类型自动转换\n",
    "assert repr(tensor_x) == 'Tensor([1, 10], \"float32\")' # 标准表示形式\n",
    "\n",
    "# 显示Tensor对象（触发__repr__方法）\n",
    "tensor_x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fc118214",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 123.321\n",
    "tensor_x = Tensor.from_scalar(x, dtype=\"float16\")\n",
    "assert tensor_x.shape == []\n",
    "assert tensor_x.ndim == 0\n",
    "assert tensor_x.dtype == \"float16\"\n",
    "assert repr(tensor_x) == 'Tensor([], \"float16\")'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a8a88792",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tensor([1, 10], \"float16\")"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Tensor.from_scalar(np.random.rand(1, 10), dtype=\"float16\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a15a89e8",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ai",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
